<template>
  <el-dialog :append-to-body='true' title="地图位置选择" :visible.sync="isshowmapDialog" width="50%" :show-close='false'
    :close-on-click-modal='false' top='15vh'>
    <i class="iconfont closeicon" @click='closemap'>&#xe6ce;</i>
    <div class="maparea">
      <el-input class="searchmap" @input='changeinput' size="large" v-model="addsearch"></el-input>
      <!-- 搜索的列表 -->
      <div class="searchList" v-if="searchList.length>0&&iscloseSearch">
        <ul>
          <li v-for="(item,index) in searchList" :key='index' @click="clicksearchitem(item)">{{item.name}}</li>
        </ul>
      </div>
      <el-amap vid="amapDemo" :zoom="17" jogEnable='true' rotateEnable style="width:100%;height:400px;" :plugin="plugin"
        :center='center' :events="events">
        <!-- 地图标记 -->
        <el-amap-marker animation='AMAP_ANIMATION_BOUNCE' icon='https://oss.juchehulian.com/_platform/normal/3VgdZ31610419091.png'
          v-for="(marker,index) in markers" :events="marker.events" :position="marker.position" :key="index"></el-amap-marker>
      </el-amap>
    </div>
    <span slot="footer" class="dialog-footer" v-if="isshowfooter">
      <el-button @click="closemap" size="medium">取 消</el-button>
      <el-button type="primary" @click="affirmMap" size="medium">确 定</el-button>
    </span>
  </el-dialog>
</template>


<script>
  export default {
    data() {
      const that = this;
      return {
        //是否关闭搜索框 列表
        iscloseSearch: true,
        //搜索的文字
        addsearch: '',
        //搜索的列表
        searchList: [],
        //初始化定位
        center: [121.59996, 31.197646],
        //坐标
        lng: 0,
        lat: 0,
        loaded: false,
        //地图事件
        events: {
          'click': (e) => {
            that.lng = e.lnglat.lng
            that.lat = e.lnglat.lat
            //点击地图获取位置信息
            that.clickMap(e.lnglat.lng, e.lnglat.lat)
            that.center = [that.lng, that.lat]
            let geocoder = new AMap.Geocoder({
              radius: 1000,
              extensions: 'all'
            })
            geocoder.getAddress([that.lng, that.lat], function(status, result) {
              // console.log(result)
              if (status === 'complete' && result.info === 'OK') {
                if (result && result.regeocode) {
                  // console.log(result.regeocode.formattedAddress)
                  that.addsearch = result.regeocode.formattedAddress
                }
              }
            })
          },
        },
        markers: [
          // 标记点位置
          {
            position: [116.40, 39.90],
            visible: true,
            draggable: false,
          }
        ],
        // 获取当前地图的插件位置
        plugin: [{
            enableHighAccuracy: true, //是否使用高精度定位，默认:true
            timeout: 100000, //超过10秒后停止定位，默认：无穷大
            maximumAge: 0, //定位结果缓存0毫秒，默认：0
            convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
            showButton: false, //显示定位按钮，默认：true
            buttonPosition: 'RB', //定位按钮停靠位置，默认：'LB'，左下角
            showMarker: false, //定位成功后在定位到的位置显示点标记，默认：true
            showCircle: true, //定位成功后用圆圈表示定位精度范围，默认：true
            panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
            zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：f
            extensions: 'all',
            pName: 'Geolocation',
            events: {
              init(o) {
                //如果只有地址 那么就是导入的地址
                if (that.userSelectinfo.address && !that.userSelectinfo.lat && !that.userSelectinfo.lng) {
                  //自动定位到成都天府广场
                  that.userSelectinfo = {
                    address: that.userSelectinfo.address,
                    lat: 30.658499,
                    lng: 104.066177
                  }
                }
                //如果之前用户选择过那么显示 页面
                if (Object.values(that.userSelectinfo).length > 0) {
                  let addinfo = Object.values(that.userSelectinfo)
                  that.addsearch = addinfo[0]
                  that.center = [addinfo[2], addinfo[1]];
                  let position = that.markers[0].position;
                  that.markers[0].position = [addinfo[2], addinfo[1]];
                  return;
                }
                // o 是高德地图定位插件实例
                o.getCurrentPosition((status, result) => {
                  if (result && result.position) {
                    that.addsearch = result.formattedAddress
                    // 将当前经纬度给中心点
                    that.lat = result.position.lat
                    that.lng = result.position.lng
                    that.center = [result.position.lng, result.position.lat];
                    // 将当前经纬度给标记点
                    that.markers[0].position = that.center;
                    that.loaded = true;
                    // 页面渲染好后
                    that.$nextTick();
                  }
                });
              }
            }
          },
          {
            // 搜索
            pName: 'PlaceSearch',
            events: {
              //初始化搜索
              init(instance) {

              }
            }
          }
        ],
      }
    },
    props: {
      //是否显示底部按钮
      isshowfooter: {
        type: Boolean,
        default: true
      },
      //是否显示地图弹窗？
      isshowmapDialog: {
        type: Boolean,
        default: false
      },
      //接收用户选择的参数
      userSelectinfo: {
        type: Object,
        default: () => {
          return {}
        }
      },
      //是否重建
      reFresh: {
        type: Boolean,
        default: true
      }
    },

    methods: {
      //用户选中自己搜索的地址
      clicksearchitem(item) {
        this.addsearch = item.name
        //获取用户选中的坐标点
        let userSelectlng = item.location.lng
        let userSelectlat = item.location.lat

        this.lng = userSelectlng
        this.lat = userSelectlat
        //更改坐标点
        this.center = [userSelectlng, userSelectlat]
        //更改坐标图标位置
        let position = this.markers[0].position;
        this.markers[0].position = [userSelectlng, userSelectlat];
        this.iscloseSearch = false
      },
      //监听用户的输入地图事件
      changeinput(val) {
        if (val.trim() == '') {
          return
        }
        this.iscloseSearch = true
        this.initSearch(val)
      },
      //用户确认地图
      affirmMap() {
          let mapparams={}
        if(this.lat==0 && this.lng==0){
          mapparams={
          address: this.addsearch,
          lat: this.userSelectinfo.lat,
          lng: this.userSelectinfo.lng
        }
        }else{
          mapparams = {
            address: this.addsearch,
            lat: this.lat,
            lng: this.lng
          }
        }

        this.$emit('affirmMaps', mapparams)
      },
      //用户关闭map
      closemap() {
        this.$emit('closemap')
      },
      //搜索地图
      onSearchResult(val) {

      },
      //点击地图获取到的位置
      clickMap(lng, lat) {
        let position = this.markers[0].position;
        this.markers[0].position = [lng, lat];

      },
      initSearch(val) {
        let searchadd = new AMap.PlaceSearch({
          pageSize: 8
        })
        searchadd.search(val, (st, re) => {
          console.log(re)
          if (st == 'complete') {
            this.searchList = re.poiList.pois
          } else {
            this.searchList = []
          }
        })
      }

    }
  }
</script>

<style scoped lang='scss'>
  .closeicon {
    position: absolute;
    right: 20px;
    top: 15px;
    cursor: pointer;
    font-size: 24px;
    color: hsla(0, 0%, 40%, .6784313725490196);
    &:hover {
      color: $base-color-default;
    }
  }
  .search-box {
    position: absolute;
    top: 96px;
    left: 30px;
  }
  .searchmap {
    position: absolute;
    top: 96px;
    left: 30px;
    width: 450px;
    height: 50px;
    z-index: 999;
  }
  .searchList {
    position: absolute;
    top: 138px;
    left: 30px;
    z-index: 9999;
    background-color: #fff;
    width: 450px;
    padding: 20px;
    box-sizing: border-box;
    border-radius: 5px;
    ul {
      list-style: none;
      padding: 0;
      margin: 0;
      li {
        border-bottom: 1px solid #f5f5f5;
        line-height: 38px;
        color: #333;
        padding-left: 10px;
        cursor: pointer;
        &:last-child {
          border-bottom: none;
        }
        &:hover {
          background-color: #f5f7fa;
        }
      }
    }
  }
</style>
